#!/usr/bin/env python
# -*- coding: utf-8 -*-

import logging
import tempfile
from gaeo.controller import Controller
from application import models
import settings
import boto

config = boto.config
config.add_section('Credentials')
config.set('Credentials', 'gs_access_key_id', settings.GS_ACCESS_KEY_ID)
config.set('Credentials', 'gs_secret_access_key', settings.GS_SECRET_ACCESS_KEY)

class User(Controller):
    def login(self):
        self.view.breadcrumb = '<a href="/" class="breadcrumb-link">首頁</a> &raquo; 加入或登入'
        self.view.page_title = u'加入或登入 &laquo; Taipei GTUG Forum'
        
    def create(self):
        self.view.user_type = self.params.get('user_type')
        self.view.thumbnail = self.params.get('thumbnail')
        self.view.breadcrumb = '<a href="/" class="breadcrumb-link">首頁</a> &raquo; 加入或登入 &raquo; 建立論壇帳號'
        self.view.page_title = u'建立論壇帳號 &laquo; Taipei GTUG Forum'

    def auth(self):
        from google.appengine.api import users
                
        curl = self.params.get('curl', '/')
        
        auth_user = users.get_current_user()
        key = models.User.create_key_name(auth_user)
        user = models.User.get_by_key_name(key)
        if user is None: # 1st time login
            self.redirect('/user/register?curl=%s' % curl)
        else:
            self.session['userKey'] = key
            self.redirect(curl)
            
    def register(self):
        from google.appengine.api import users
        request_method = self.request.method
        if request_method == 'GET':
            self.view.curl = self.params.get('curl', '/')
            self.view.hide_login = True
            self.view.login_acct = users.get_current_user()
            self.view.page_title = u'註冊帳號 &laquo; Taipei GTUG Forum'
            self.view.error = int(self.params.get('error', '0'))
        elif request_method == 'POST':
            from google.appengine.ext import db
            try:
                logging.info(self.params)
                auth_user = users.get_current_user()
                curl = self.params.get('curl', '/')
                raw_username = self.params.get('username')
                raw_email = self.params.get('email')
                
                u = models.User.get_by_username(raw_username)
                if u is not None:
                    self.redirect('/user/register?error=1&curl=' + curl)
                    return
                
                raw_key = models.User.create_key_name(auth_user)
                def tx(name, email, key):
                    u = models.User(key_name=key,
                                    account=auth_user,
                                    name=name,
                                    email=db.Email(email))
                    u.put()
                db.run_in_transaction(tx, raw_username, raw_email, raw_key)
                self.session['userKey'] = raw_key
                logging.info(curl)
                self.redirect(curl)
            except:
                raise
            
    
    # e.g., /u/ericsk
    def show(self):
        self.view.user = models.User.get_by_username(self.params['username'])
        self.view.page_title = u'使用者 %s 的個人檔案 － Taipei GTUG Forum' % self.view.user.display_name
    
    # e.g., /user/settings
    def settings(self):
        request_method = self.request.method
        if request_method == 'GET':
            self.view.page_title = u'用戶設定 - Taipei GTUG Forum'
        else:
            u = self.params['user']
            t = ''
            if 'thumb' in u and len(u['thumb']) > 0:
                from google.appengine.api import images
                
                avatar = images.resize(u['thumb'], 48, 48, images.PNG)
                
                dst_uri = boto.storage_uri(settings.GS_BUCKET_NAME, "gs")
                new_dst_uri = dst_uri.clone_replace_name('%s.png' % self.view.member.display_name)
                dst_key = new_dst_uri.new_key()

                tmp = tempfile.TemporaryFile()
                tmp.write(avatar)
                tmp.seek(0)
                dst_key.set_contents_from_file(tmp)
                
                uri = boto.storage_uri('%s/%s.png' % (settings.GS_BUCKET_NAME, self.view.member.display_name), "gs")
                key = uri.get_key()
                key.open_read()
                key.set_acl('public-read')
                t = '%s.png' % self.view.member.display_name
                
            self.view.member.update(email=u.get('email', ''),
                                    profile=u.get('profile', ''),
                                    website=u.get('website', ''),
                                    thumb=t)
            self.redirect('/user/settings')
    
    def logout(self):
        self.session.destroy()
        self.set_cookie(settings.SESSION_COOKIE_NAME, '', -settings.SESSION_COOKIE_TIMEOUT)
        self.redirect('/')